package com.glqiang.security;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.Assert;

import java.util.Collection;

/**
 * @author glqiang
 * @date 2022/11/17 20:34
 * 自定义认证token
 */
public class CustomAuthenticationToken extends AbstractAuthenticationToken {
    /**
     * 这里的 principal 在未认证的时候指的是 账号，认证后是用户信息
     */
    private final Object principal;

    /**
     * 认证的凭证，密码、验证码等
     */
    private Object credentials;

    public CustomAuthenticationToken(Object principal, Object credentials) {
        super(null);
        this.principal = principal;
        this.credentials = credentials;
        setAuthenticated(false);
    }

    public CustomAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        this.credentials = credentials;
        super.setAuthenticated(true); // must use super, as we override
    }

    /**
     * 未经认证的
     *
     * @param principal   账号
     * @param credentials 密码
     * @return EmailAuthenticationToken
     */
    public static CustomAuthenticationToken unauthenticated(Object principal, Object credentials) {
        return new CustomAuthenticationToken(principal, credentials);
    }

    /**
     * 认证过的
     *
     * @param principal   用户信息
     * @param credentials 密码
     * @param authorities 权限信息
     * @return EmailAuthenticationToken
     */
    public static CustomAuthenticationToken authenticated(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
        return new CustomAuthenticationToken(principal, credentials, authorities);
    }

    @Override
    public Object getCredentials() {
        return this.credentials;
    }

    @Override
    public Object getPrincipal() {
        return this.principal;
    }

    @Override
    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        Assert.isTrue(!isAuthenticated, "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        super.setAuthenticated(false);
    }

    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
        this.credentials = null;
    }
}
